//
//  ZcVideoPreviewViewController.m
//  智能控制系统
//
//  Created by Rankin on 16/2/27.
//
//

#import "ZcVideoPreviewViewController.h"

@interface ZcVideoPreviewViewController ()<HKPlayerDelegate>

@end

@implementation ZcVideoPreviewViewController
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (id)init{
    self = [super init];
    if(self){
        
    }
    return self;
}

- (id)initWithUmid:(NSString*)umid deviceUserId:(NSString*)deviceUserId devicePassword:(NSString*)pwd
           recfile:(HKSRecFile *)recfile channelNo:(int)channelNo{
    self = [self initWithNibName:@"VideoPreviewView" bundle:[NSBundle mainBundle]];
    if(self){
        self.P2PServe = @"app.umeye.cn";
        self.serverPort = 8300;
        self.deviceUMID = umid;
        self.deviceUserID = deviceUserId;
        self.devicePassword = pwd;
        self.channelNo = channelNo;
        
        self.recfile = recfile;
        
        self.minTime = recfile.startTime.hour*60*60 + recfile.startTime.minute*60 + recfile.startTime.second;
        self.maxTime = recfile.endTime.hour*60*60 + recfile.endTime.minute*60 +recfile.endTime.second;
        self.currentTime = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    self.playerClient = [[HKSDeviceClient alloc]init];//初始化播放器
    [self.playerClient.view setFrame:CGRectMake(0,0,self.videoDisplayView.frame.size.width,self.videoDisplayView.frame.size.height)];
    self.playerClient.view.layer.borderWidth = 0;
    self.playerClient.audioEnabled = YES;
    self.playerClient.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin
    | UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleHeight
    | UIViewAutoresizingFlexibleWidth;
    [self.playerClient setDisplayViewColor:[UIColor redColor]];
    
    [self.videoDisplayView addSubview :self.playerClient.view];
    self.playerClient.delegate = self;
    
    [self.backBut addTarget:self action:@selector(PopToBack:) forControlEvents:UIControlEventTouchDown];
    
    [self.playBut addTarget:self action:@selector(onPlayAction:) forControlEvents:UIControlEventTouchDown];
    [self.playBut setImage:[UIImage imageNamed:@"video_stop"] forState:UIControlStateSelected];
    
    
    self.minTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d",self.recfile.startTime.hour,self.recfile.startTime.minute,self.recfile.startTime.second];
    
    self.maxTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d",self.recfile.endTime.hour,self.recfile.endTime.minute,self.recfile.endTime.second];
    
//    HKSDeviceCodecItem *codecItem = [[HKSDeviceCodecItem alloc] init];
//    codecItem.iChNo = self.playerClient.deviceChannel;
//    if ([self.playerClient deviceCodecInfo:codecItem] == HKS_NPC_D_MPI_MON_ERROR_SUC) {
//        if (codecItem.pVideoFormat.iResolution == HKS_NPC_D_MON_VEDIO_RESOLUTION_QCIF
//            || codecItem.pVideoFormat.iFrameRate < 7) {
//            codecItem.pVideoFormat.iResolution = HKS_NPC_D_MON_VEDIO_RESOLUTION_QVGA;
//            codecItem.pVideoFormat.iFrameRate = 7;
//            [self.playerClient setDeviceCodecInfo:codecItem];
//        }
//        
//    }
    
    
    //添加手势 右滑后退
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleBackRecognizer:)];
    [self.videoDisplayView addGestureRecognizer:swipe];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

-(void)handleBackRecognizer:(UISwipeGestureRecognizer*)recognizer{
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight){
        NSLog(@"右划后退手势");
        [self PopToBack:nil];
    }
    
}
- (void)initPlayer{
    [self.playerClient setDeviceConnParam:self.P2PServe
                               serverPort:self.serverPort
                               deviceUMID: self.deviceUMID
                             deviceUserID:self.deviceUserID
                           devicePassword:self.devicePassword
                            deviceChannel:self.channelNo
                             deviceStream:1
                             deviceVendor:-1];
    
    [self.playerClient setRecFileConnParam:self.recfile];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)PopToBack:(id)sender{
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation!=UIInterfaceOrientationPortrait) {
        [[UIDevice currentDevice]setValue:[NSNumber numberWithInt: UIInterfaceOrientationPortrait] forKey:@"orientation"];
        return;
    }
    
    
    //    [self.navigationController popToRootViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //退出释放对象
            [self.playerClient stop:YES exit:YES];
            [_playStatusCheckTimer invalidate];
            _playStatusCheckTimer = nil;
        });
    }];
}

- (void)startVideoPreview{
    [self initPlayer];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [self.playerClient stop:YES exit:YES];
        NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.playerClient start];
            NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
            
        });
    });
    
    if(_playStatusCheckTimer)
    {
        [_playStatusCheckTimer invalidate];
        _playStatusCheckTimer = nil;
    }
    _playStatusCheckTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updatePlayStatus) userInfo:nil repeats:YES];
}

- (void)onPlayAction:(id)sender{
    UIButton* select = (UIButton*)sender;
    [select setSelected:!select.isSelected];
    if(select.isSelected){
        [self startVideoPreview];
    }else{
        [self stopPlay];
    }
    
}

- (void)stopPlay{
    [self.playerClient stop:YES];
}



-(void)updatePlayStatus{
    NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
}

- (IBAction)onSliderValueChange:(id)sender {
    UISlider *slider = (UISlider*)sender;
    self.currentTime  = (int)(slider.value*(self.maxTime-self.minTime));
    [self.playerClient controlRecord:HKS_NPC_D_MON_PLAY_CTRL_SET_PLAY_POS data:self.currentTime];
}

#pragma 播放器监听delegate
- (void)playerFeedback:(id)player status:(int)status currentTime:(long)aCurrentTime totalTime:(long)aTotalTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog([[NSString alloc]initWithFormat:@"播放时间%3l",aCurrentTime ]);
        self.processCtr.value = (double)aCurrentTime/(double)aTotalTime;
    });
    
}

#pragma  挂起恢复
- (void)onPause
{
    [self stopPlay];
}

- (void)onResume
{
    [self startVideoPreview];
}

@end
